import {
  asyncRouterMap,
  constantRouterMap
} from '@/router'
import {
  topRouterMap
} from "@/router/topRouter";
import * as mutils from '@/utils/mUtils'
import store from '@/store'
import {
  Layout,
  Content
} from "../../layout"; // 页面整体布局

// 循环追加顶栏菜单
function addTopRouter() {
  asyncRouterMap.forEach((item) => {
    if (item.children && item.children.length >= 1) {
      item.children.forEach((sitem) => {
        topRouterMap.forEach((citem) => {
          if (sitem.name === citem.parentName) {
            let newChildren = item.children.concat(citem.topmenulist); // arr
            item.children = newChildren;
          }
        })
      })
    }
  })
  return asyncRouterMap;
}

// 获取到当前路由对应顶部子菜单
function filterTopRouters(data) {
  // let topRouters = topRouterMap.find((item) => {
  //   return item.parentName === data.name
  // })
  // if (!mutils.isEmpty(topRouters)) {
  //   return topRouters.topmenulist;
  // }
}

/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  // roles为权限身份数组
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.indexOf(role) >= 0)
  } else {
    return true
  }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param roles
 */
function filterAsyncRouter(asyncRouterMap, roles) {
  // 返回满足条件的子路由对象
  const accessedRouters = asyncRouterMap.filter(route => {

    if (hasPermission(roles, route)) {

      if (route.children && route.children.length) {
        // route.children重新过滤赋值;
        route.children = filterAsyncRouter(route.children, roles)
      }
      return true // 返回该权限路由对象;
    }
    return false
  })
  return accessedRouters
}
function generateRouter(data, cmp, children) {
  const cmpMap = new Map();
  const dataMap = new Map();
  let arrList = []
  cmp.forEach(item => {
    // console.log(item, "TOP.OPERATE_M,")
    item.next_level_info.forEach(itmechild => {
      if (itmechild.name == "用户信息" || itmechild.name == "登录日志" || itmechild.name == "客户满意度") {
        arrList.push(itmechild.api)
      }
      itmechild.next_level_info.forEach(itmeNext => {
        if (itmeNext.name == "查看" || itmeNext.name == "已处理列表查看" || itmeNext.name == "客户收入统计") {
          arrList.push(itmeNext.api)
        }
      })
    })
  });
  store.commit("SET_CONTROL", arrList);
  for (var i = 0; i < data.length; i++) {
    if (data[i].path != null) {
      dataMap.set(data[i].path, {
        path: data[i].path == undefined ? "" : data[i].path,
        name: data[i].name,
        leve: data[i].leve,
        noDropdown: data[i].noDropdown,
        component: data[i].component,
        meta: data[i].meta,
        children: [],
        belongs: data[i].belongs
      });
      if (data[i].children != null) {
        for (var j = 0; j < data[i].children.length; j++) {
          var arrListTrue = arrList.indexOf(data[i].children[j].limits)
          if (arrListTrue > -1) {
            dataMap.forEach(item => {
              if (item.name == data[i].children[j].leve) {
                item.children.push(data[i].children[j])
              }
            })
          } else {

          }

        }
      }
    }

  }
  return dataMap
}
function extractPathsAndMetaWithChildren(menuData) {
  const result = [];
  for (const menu of menuData) {
    if (menu.children && menu.children.length > 0) {
      for (const child of menu.children) {
        result.push({
          urL: child.path,
          meta: child.meta
        });
      }
    }
  }
  store.commit('ROUTE_JUMP', result)
  //  // console.log(result,"resultresult")
  // return result;
  // const result = [];
  // function processItem(item) {
  //   if (item.path && item.meta) {
  //     const newItem = {
  //       path: item.path,
  //       meta: item.meta,
  //     };
  //     if (item.children && Array.isArray(item.children)) {
  //       newItem.children = item.children.map((child) => {
  //         return {
  //           path: child.path,
  //           meta: child.meta,
  //         };
  //       });
  //     }
  //     result.push(newItem);
  //   }
  // }

  // if (Array.isArray(data)) {
  //   data.forEach((item) => {
  //     processItem(item);
  //   });
  // }
  // flattenPathsAndMetaWithChildren(result)
}
// function flattenPathsAndMetaWithChildren(data) {
//   const result = [];

//   function processItem(item) {
//     if (item.path && item.meta) {
//       const newItem = {
//         path: item.path,
//         meta: item.meta,
//       };
//       if (item.children && Array.isArray(item.children)) {
//         item.children.forEach((child) => {
//           if (child.path && child.meta) {
//             result.push({
//               path: child.path,
//               meta: child.meta,
//             });
//           }
//         });
//       }
//       result.push(newItem);
//     }
//   }

//   if (Array.isArray(data)) {
//     data.forEach((item) => {
//       processItem(item);
//     });
//   }
//   store.commit('ROUTE_JUMP', result)
// }
const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: [],
    topRouters: [],
    topTitle: '',
    menuIndex: 0,
    leftRouters: [],
    RouteJump: [],
  },
  getters: {
    permission_routers: state => state.routers, // 所有路由
    addRouters: state => state.addRouters, // 权限过滤路由
    topRouters: state => state.topRouters, // 顶部三级路由
    topTitle: state => state.topTitle, // 顶部的title
    menuIndex: state => state.menuIndex, // 顶部菜单的index
    leftRouters: state => state.leftRouters
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers // 权限路由
      state.routers = constantRouterMap.concat(routers) // 总路由

    },
    CLICK_INNER_LEFT_MENU: (state, data) => {
      state.topRouters = data.titleList;
    },
    CLICK_TOP_MENU: (state, data) => {
      state.topTitle = data.title
      state.menuIndex = data.menuIndex
      if (data.menuIndex) {
        state.leftRouters = state.routers.filter(item => item.belongs == data.menuIndex)
      }
    },
    ROUTE_JUMP: (state, data) => {
      state.RouteJump = data;
    }
  },
  actions: {
    // 根据角色，重新设置权限路由;并保存到vuex中,SET_ROUTERS;
    GenerateRoutes({
      commit
    }, data) {
      return new Promise(resolve => {
        var accesList = []
        var TiemsList = generateRouter(asyncRouterMap, data.menu, accesList);
        var namelist = [...TiemsList.values()]
        var regroup = namelist.filter((item) => item.children.length > 0)
        extractPathsAndMetaWithChildren(regroup, "regroupregroup")
        commit('SET_ROUTERS', regroup)
        resolve()
      })
    },
    ClickLeftInnerMenu({
      commit
    }, data) {
      commit('CLICK_INNER_LEFT_MENU', data)
    },
    ClickTopMenu({
      commit
    }, data) {
      commit('CLICK_TOP_MENU', data)
    }
  }
}

export default permission